package com.zmn.oms.dubbo.impl.zmn.third.shunfeng;

import org.apache.dubbo.config.annotation.Service;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.dubbo.dto.zmn.third.shunfeng.ShunfengOrderDataDRO;
import com.zmn.oms.dubbo.interfaces.zmn.third.shunfeng.ShunfengRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.third.shunfeng.ShunfengConsts;
import com.zmn.oms.third.shunfeng.ShunfengUtil;
import com.zmn.oms.third.shunfeng.api.SFOrderOuterDataDTO;
import com.zmn.oms.third.shunfeng.service.ShunfengService;
import com.zmn.tapi.common.aliyun.sts.AccessKeyInfo;
import com.zmn.tapi.dubbo.interfaces.aliyun.OssRemoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.Optional;

/**
 * @author xiewenbing
 * @date:2020/12/14 15:30
 * description: 顺丰安装的H5页面接口，用来查询顺丰安装渠道订单资料，保存等
 */
@Slf4j
@Api(value = "顺丰安装H5接口", tags = {"顺丰安装H5接口"})
@Service(loadbalance = "roundrobin", timeout = 5000, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class ShunfengRemoteServiceImpl implements ShunfengRemoteService {

    @Autowired
    private ShunfengService shunfengService;

    @Reference(version = com.zmn.tapi.dubbo.DubboConsts.INTERFACE_VERSION, check = false)
    private OssRemoteService ossRemoteService;


    /**
     * 获取订单的相关信息
     *
     * @param orderId
     * @param completeImageNumber
     * @param failedImageNumber
     * @return
     */
    @Override
    @ApiOperation(value = "查询订单资料")
    public ResponseDTO<ShunfengOrderDataDRO> getOrderData(Long orderId, Integer completeImageNumber, Integer failedImageNumber) {

        log.info("【{}】 H5接口查询订单资料【{}】",ShunfengConsts.CHANNEL_NAME, orderId);
        if (NumberUtil.isNullOrZero(orderId)) {
            return ResponseDTO.fail("订单id不能为空");
        }

        ShunfengOrderDataDRO orderDataDRO;
        try {
            SFOrderOuterDataDTO orderOuterDataDTO = shunfengService.getOrderOutData(orderId);
            if (Objects.isNull(orderOuterDataDTO)) {
                return ResponseDTO.fail("查询失败");
            }

            orderDataDRO = BeanMapper.map(orderOuterDataDTO,ShunfengOrderDataDRO.class);
            orderDataDRO.setImageUploadUrl(ShunfengConsts.IMAGE_URL);
            orderDataDRO.setImageUploadCode(ShunfengConsts.CLIENT_CODE);

            // 完成图片上传的digest
            if (NumberUtil.isNotNullOrZero(completeImageNumber)) {
                // 计算签名 Base64(MD5 (clientCode + imageNumber + imageType + waybillNo +taskCode+ md5key) )
                StringBuilder sbDigest = new StringBuilder();
                sbDigest.append(ShunfengConsts.CLIENT_CODE).append(completeImageNumber).
                        append(ShunfengConsts.IMAGE_TYPE_SERVICE_COMPLETE).append(orderOuterDataDTO.getWaybillNo()).
                        append(orderOuterDataDTO.getTaskCode()).append(ShunfengConsts.IMAGE_MD5_KEY);

                orderDataDRO.setCompleteImageUploadDigest(ShunfengUtil.encryptData(sbDigest.toString()));
            }

            // 安装异常图片上传的digest
            if (NumberUtil.isNotNullOrZero(failedImageNumber)) {
                StringBuilder sbDigest = new StringBuilder();
                sbDigest.append(ShunfengConsts.CLIENT_CODE).append(failedImageNumber).
                        append(ShunfengConsts.IMAGE_TYPE_INSTALL_FAILED).append(orderOuterDataDTO.getWaybillNo()).
                        append(orderOuterDataDTO.getTaskCode()).append(ShunfengConsts.IMAGE_MD5_KEY);

                orderDataDRO.setFailedImageUploadDigest(ShunfengUtil.encryptData(sbDigest.toString()));

            }

            // tapi文件上传的参数获取和设置，用于图片上传给zmn平台
            ResponseDTO<AccessKeyInfo> accessKeyInfoResponseDTO = ossRemoteService.applyAccessKey("mapp-h5","");
            if (accessKeyInfoResponseDTO.isSuccess() && Objects.nonNull(accessKeyInfoResponseDTO.getData())) {
                orderDataDRO.setAccessKeyId(accessKeyInfoResponseDTO.getData().getAccessKeyId());
                orderDataDRO.setAccessKeySecret(accessKeyInfoResponseDTO.getData().getAccessKeySecret());
                orderDataDRO.setSecurityToken(accessKeyInfoResponseDTO.getData().getSecurityToken());
            } else {
                log.info("【{}】 申请H5上传文件Key失败【{}】",ShunfengConsts.CHANNEL_NAME, accessKeyInfoResponseDTO.toString());
            }

        } catch (OmsBaseException omsBaseException) {

            log.info("【{}】 H5接口查询订单资料异常【{}】",ShunfengConsts.CHANNEL_NAME, omsBaseException);
            return ResponseDTO.fail(Optional.ofNullable(omsBaseException.getMessage()).orElse("查询异常"));

        } catch (Exception exception) {
            log.info("【{}】 H5接口查询订单资料异常【{}】",ShunfengConsts.CHANNEL_NAME, exception);
            return ResponseDTO.fail(Optional.ofNullable(exception.getMessage()).orElse("查询异常"));
        }

        log.info("【{}】 H5接口查询订单资料完成【{}】【{}】",ShunfengConsts.CHANNEL_NAME, orderId, orderDataDRO);
        return ResponseDTO.success(orderDataDRO);
    }

    /**
     * 同步订单安装异常
     *
     * @param orderId
     * @param failedReason
     * @param imageUrl
     * @return
     */
    @Override
    @ApiOperation(value = "同步顺丰订单安装异常信息")
    public ResponseDTO syncOrderInstallFailed(Long orderId, String failedReason, String imageUrl) {

        log.info("【{}】 H5接口同步安装异常【{}】【{}】【{}】",ShunfengConsts.CHANNEL_NAME, orderId, failedReason, imageUrl);
        if (NumberUtil.isNullOrZero(orderId) || StringUtils.isBlank(failedReason)) {
            return ResponseDTO.fail("订单Id/异常原因 不能为空");
        }


        try {
            shunfengService.syncOrderFailed(orderId,failedReason,imageUrl);
        } catch (OmsBaseException omsBaseException) {

            log.info("【{}】 H5接口同步安装失败异常【{}】",ShunfengConsts.CHANNEL_NAME, omsBaseException);
            return ResponseDTO.fail(Optional.ofNullable(omsBaseException.getMessage()).orElse("同步数据异常"));

        } catch (Exception exception) {
            log.info("【{}】 H5接口同步安装失败异常【{}】",ShunfengConsts.CHANNEL_NAME, exception);
            return ResponseDTO.fail(Optional.ofNullable(exception.getMessage()).orElse("同步数据异常"));
        }

        log.info("【{}】 H5接口同步安装异常完成【{}】",ShunfengConsts.CHANNEL_NAME, orderId);
        return ResponseDTO.success();
    }

    /**
     * 同步订单安装完成图片的url
     *
     * @param orderId
     * @param imageUrl
     * @return
     */
    @Override
    @ApiOperation(value = "同步顺丰订单安装完成的图片信息")
    public ResponseDTO saveOrderCompleteImageUrl(Long orderId, String imageUrl) {

        log.info("【{}】 H5接口同步安装完成【{}】【{}】",ShunfengConsts.CHANNEL_NAME, orderId, imageUrl);
        if (NumberUtil.isNullOrZero(orderId) || StringUtils.isBlank(imageUrl)) {
            return ResponseDTO.fail("订单Id/图片url 不能为空");
        }

        try {
            shunfengService.saveOrderCompleteImage(orderId,imageUrl);
        } catch (OmsBaseException omsBaseException) {

            log.info("【{}】 H5接口同步安装完成异常【{}】",ShunfengConsts.CHANNEL_NAME, omsBaseException);
            return ResponseDTO.fail(Optional.ofNullable(omsBaseException.getMessage()).orElse("同步数据异常"));

        } catch (Exception exception) {
            log.info("【{}】 H5接口同步安装完成异常【{}】",ShunfengConsts.CHANNEL_NAME, exception);
            return ResponseDTO.fail(Optional.ofNullable(exception.getMessage()).orElse("同步数据异常"));
        }

        log.info("【{}】 H5接口同步安装完成完成【{}】",ShunfengConsts.CHANNEL_NAME, orderId);
        return ResponseDTO.success();
    }
}
